from datetime import datetime
import re
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
# Create your views here.
from myadmin.models import DietPlan, SystemNotice, UserDietRecords, Users


#后台管理首页
def index(request):
    """控制面板首页，统计各类数据"""
    today = datetime.now().date()
    now = datetime.now()
    
    # 统计今日饮食记录数
    daily_compliance_count = UserDietRecords.objects.filter(
        record_time__date=today
    ).count()
    
    # 统计今日新增用户数
    new_users_count = Users.objects.filter(
        created_at__date=today
    ).count()
    
    # 统计待处理饮食计划数（未激活状态）
    pending_diets_count = DietPlan.objects.filter(
        is_active=False
    ).count()
    
    # 统计新系统通知数（分两步查询避免Q对象）
    # 1. 查询永不过期的有效通知
    never_expire_notices = SystemNotice.objects.filter(
        is_active=True,
        publish_time__lte=now,
        expire_time__isnull=True
    ).count()
    
    # 2. 查询未过期的有效通知
    not_expired_notices = SystemNotice.objects.filter(
        is_active=True,
        publish_time__lte=now,
        expire_time__isnull=False,  # 确保有过期时间
        expire_time__gte=now
    ).count()
    
    # 总通知数 = 永不过期 + 未过期
    system_notices_count = never_expire_notices + not_expired_notices
    
    context = {
        'daily_compliance_count': daily_compliance_count,
        'new_users_count': new_users_count,
        'pending_diets_count': pending_diets_count,
        'system_notices_count': system_notices_count,
    }
    return render(request,'myadmin/index/index.html')


#管理员登录表单
def login(request):
    return render(request,'myadmin/index/login.html')

#执行管理员登录
def dologin(request):
    try:
        # 获取表单输入的用户名和密码（去除空格）
        login_input = request.POST.get('login','').strip()
        #username = request.POST.get('username', '').strip()
        #email = request.POST.get('email', '').strip()
        input_pass = request.POST.get('pass', '').strip()
        # 获取验证码
        verifycode = request.POST.get('verifycode', '').strip()
        # 验证验证码
        if not verifycode:
            return render(request, "myadmin/index/login.html", {"info": "请输入验证码"})
        # 从session获取验证码进行验证
        if verifycode != request.POST.get('verifycode', ''):
            return render(request, "myadmin/index/login.html", {"info": "验证码错误"})
        

        # 验证登录账号（用户名或邮箱）和密码不为空
        if not login_input or not input_pass:
            return render(request, "myadmin/index/login.html", {"info": "登录账号或密码不能为空"})
        

        # 判断输入的是邮箱还是用户名
        email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
        is_email = re.match(email_pattern, login_input)
        
        # 根据用户名或邮箱查询用户信息
        try:
            if is_email:
                # 邮箱登录：通过邮箱查询用户
                user = Users.objects.get(email=login_input)
            else:
                # 用户名登录：通过用户名查询用户
                user = Users.objects.get(username=login_input)
        except Users.DoesNotExist:
            return render(request, "myadmin/index/login.html", {"info": "用户不存在"})
        

        # 验证是否为管理员（status=6）
        if user.status != 6:
            return render(request, "myadmin/index/login.html", {"info": "非管理员账号，无法登录"})

        # 直接对比明文密码（数据库存储明文）
        if user.password == input_pass:
            # 登录成功后，通过在cookie中存储用户名来标识登录状态
            response = redirect(reverse("myadmin_index"))
            response.set_cookie('adminuser', user.username)
            #response.set_cookie('adminuser_email', email)
            response.set_cookie('adminuser_created_at', user.created_at.strftime('%Y-%m-%d %H:%M:%S'))
            return response
        else:
            return render(request, "myadmin/index/login.html", {"info": "密码错误，请重新输入"})

    except Exception as err:
        print(f"登录错误详情：{err}")
        return render(request, "myadmin/index/login.html", {"info": "登录失败，请重试"})


#管理员退出
def logout(response):
    #del request.COOKIES['adminuser']
    #return redirect(reverse("myadmin_login"))
    # 退出时同时删除两个cookie
    response = redirect(reverse("myadmin_login"))
    response.delete_cookie('adminuser')
    response.delete_cookie('adminuser_created_at')
    return response


#输出验证码
def verify(request):
    #引入随机函数模块
    import random
    from PIL import Image, ImageDraw, ImageFont #要先输入pip install pillow才能用
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (145,164,247) #242是粉色，亮色很难看清楚
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width,height), bgcolor)
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0,100):
        xy = (random.randrange(0,width), random.randrange(0,height))
        fill = (random.randrange(0,255), 255, random.randrange(0,255))
        draw.point(xy,fill=fill)
    #定义验证码的备选值
    str1 = '0123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0,4):
        rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象，ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    font = ImageFont.truetype('static/arial.ttf', 21) #字体样式修改
    #构造字体颜色
    fontcolor = (255, random.randrange(0,255), random.randrange(0,255))
    #绘制4个字
    draw.text((5, -3), rand_str[0], font = font, fill=fontcolor)
    draw.text((25, -3), rand_str[1], font = font, fill=fontcolor)
    draw.text((50, -3), rand_str[2], font = font, fill=fontcolor)
    draw.text((75, -3), rand_str[3], font = font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session. 用于做进一步验证 不能用session！改成COOKIES
    request.COOKIES['verifycode'] = rand_str
    
    """
    python2的内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    #内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')


def introduction(request):
    return render(request, 'myadmin/index/introduction.html')